<?php
/**
 * 小程序首页配置
 * @Author   jiating
 */
namespace app\admin\controller;

use \think\Request;
use app\common\BaseHelper;

use app\admin\model\Tenant;
use app\admin\model\Store;
use app\admin\model\Wxframeconf;
use app\admin\model\Wxcomponentconf;
use app\admin\model\Wxframeconftmp;
use app\admin\model\Wxcomponentconftmp;
use app\admin\model\Coupon;
use app\admin\model\Groupproduct;
use app\admin\model\Storeproduct;
use app\admin\model\Integralproducts;
use app\admin\model\Article;
use app\api\controller\HomeFrame;

class Wxindex extends Base{

    public function index() {
        if(!$this->checkStore()) {
            return $this->fetch('public/alert');
        }

        $request = Request::instance();
        $param = $request->param();
        
        $tenantId = session('TENANT_ID');
        $tenant = Tenant::where('id',session('TENANT_ID'))->find();
        $store = model('store')->where(['tenantId'=>$tenantId])->order('createDate')->select();
        if(empty($store)) {
            return $this->error('请先添加门店','admin/store/index',2);
        }
        $this->assign('store',$store);

        $storeId = empty($param) ? $store[0]['id'] : $param['id'];
        if(empty($param['id']) && session('member')['roleType'] == 2 ) {
            $storeId = session('member')['storeId'];
        }
        $conf = Wxframeconf::where(['tenantId'=>$tenantId,'storeId'=>$storeId])->order('orderNo,createDate DESC')->select();
        if(empty($conf)) 
            $conf = [];
        foreach ($conf as $k => $v) {
            if($v['type'] == '5') {  //视频
                $component = Wxcomponentconf::where('frameId',$v['id'])->find();
                $conf[$k]['videoUrl'] = $component['videoUrl'];
                $conf[$k]['imgUrl'] = $component['imgUrl'];
                $conf[$k]['linkType'] = 5;
            } else if ($v['type'] == '9' ) {  //代金券
                $curTime = time();
                $url = 'http://'.$_SERVER['HTTP_HOST'].'/public/static/admin/pages/image/';
                $conf[$k]['img'] = $url . 'quan'.$v['displayType'].'-2.png';
                $list = Coupon::field('id linkId,name displayName,value2,type,value1,leftCount')->where(['tenantId'=>$tenantId,'storeId'=>$storeId])->where('endTime > '.$curTime.' and getCond = 1')->where('leftCount > 0 or isLimit = 1')->select();
                foreach ((array)$list as $k2 => $v) {
                    if($v['type'] == '无限制') {
                        $list[$k2]['condition'] = '无门槛';
                    } else {
                        $list[$k2]['condition'] = '满'.($v['value1']/100).'可用';
                    }
                     $list[$k2]['value1'] = $v['value1']/100;
                     $list[$k2]['value2'] = $v['value2']/100;
                }
                $conf[$k]['sub'] = $list;
            } else if ($v['type'] == '10' ) {  //推荐内容
               switch ($v['contentType']) {  //根据contentType取对应数据
                    case '1':  //商品
                        $list = Storeproduct::field('b.id linkId,b.title displayName,b.imgUrl,a.orderNo,b.currentPrice price')->alias('a')->join('product b','a.product_id=b.id')->order('a.orderNo')->where(['store_id'=>$storeId,'recommendation'=>1])->select();
                        break;
                    case '2':  //文章
                        $list = Article::field('id linkId,title displayName,iconUrl imgUrl,orderNo,readCount,createDate')->where(['tenantId'=>$tenantId,'recommendation'=>1])->order('orderNo')->select();
                        break; 
                    case '3':   //拼团商品
                        $list = Groupproduct::field('a.id linkId,b.title displayName,b.imgUrl,a.sort orderNo,b.groupPrice price,a.groupSuccCount')->alias('a')->join('product b','a.productId=b.id')->where(['storeId'=>$storeId,'recommendation'=>1,'status'=>['neq',2]])->order('sort')->select();
                        break;
                    case '4':  //积分兑换
                        $list = Integralproducts::field('a.productId linkId,b.title displayName,b.imgUrl,a.sort orderNo,b.integralPrice price')->alias('a')->join('product b','a.productId=b.id')->where(['storeId'=>$storeId,'recommendation'=>1])->select();
                        break;
                    default:
                        $list = [];
                }
                $conf[$k]['sub'] = $list;
            }
            // $component = Wxcomponentconf::where('frameId',$v['id'])->order('orderNo')->select();
            // $conf[$k]['sub'] = $component;
        }

        $this->assign('storeId',$storeId);
        $this->assign('tenant',$tenant);
        $this->assign('list',$conf);
        return $this->fetch();
    }

    /**
     * 根据frameId查询每个模块的具体内容,客户端分页
     * @Author   jiating
     * @DateTime 2018-05-09
     * @param    string     $frameId 模块ID
     */
    public function componentList() {
        $request = Request::instance();
        $param = $request->param();
        $id = $param['frameId'];
        // $list = Wxcomponentconf::where('frameId',$id)->order($order)->limit($start,$length)->select();
        $list = Wxcomponentconf::where('frameId',$id)->order('orderNo')->select();
        $count = Wxcomponentconf::where('frameId',$id)->count();
        $res = [
            'status' => '1',
            // 'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count
        ];
        return json($res);
    }

    /**
     * 附近门店
     *
     * @return \think\response\Json
     */
    public function componentStoreList() {
        $request = Request::instance();
        $param = $request->param();
        /*$where = [
            'a.frameId' => $param['frameId']
        ];
        $join = [
            ['__STORE__ s', 'a.storeId = s.id']
        ];
        $field = 'a.id, a.imgUrl, a.orderNo, a.displayName, a.storeId, s.name, s.province, s.city, s.district, s.address';
        $list = Wxcomponentconf::alias('a')->where($where)->join($join)->field($field)->order('orderNo')->select();
        $count = Wxcomponentconf::alias('a')->where($where)->join($join)->field($field)->count();
        $result = [
            'status' => '1',
            // 'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count
        ];*/
        $tenantId = session('TENANT_ID');
        $where = [
            'tenantId' => $tenantId
        ];
        $field = 'id, name, province, city, district, address';
        $list = Store::where($where)->field($field)->select();
        $storeimgDB = db('storeimg');
        foreach ($list as $item){
            $img = $storeimgDB->where(['storeId' => $item->id, 'tenantId' => $tenantId])->value('imgUrl');
            $item->imgUrl = $img;
        }
        $count = Store::where($where)->field($field)->count();
        $result = [
            'status' => '1',
            // 'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count
        ];

        return json($result);
    }

    /**
     * 小程序组件具体内容设置，每个门店具体设置
     * @Author   jiating
     * @DateTime 2018-05-08
     * @return   
     */
    public function component() {
        $request = Request::instance();
        $param = $request->param();
        // return $param;
        if(isset($param['id']) && $param['id']) {  //编辑操作
            $param['updateDate'] = date('Y-m-d H:i:s',time());
            $param['updateOper'] = session('member')['id'];
            $upd = Wxcomponentconf::where('id',$param['id'])->update($param);
            if($upd)
                return json(['code'=>'1','message'=>'保存成功']);
            return json(['code'=>'2','message'=>'出错，请重试']);
        }
        unset($param['id']);
        $id = BaseHelper::getUUID();
        $auto = [
            'id' => $id,
            'page' => 'home',
            'createDate' => date('Y-m-d H:i:s',time()),
            'updateDate' => date('Y-m-d H:i:s',time()),
            'createOper' => session('member')['id'],
            'updateOper' => session('member')['id'],
            'tenantId' => session('TENANT_ID')
        ];
        $data = array_merge($auto,$param);
        $add = Wxcomponentconf::insert($data);
        if($add)
            return json(['code'=>'1','message'=>'保存成功','id'=>$id]);
        return json(['code'=>'2','message'=>'出错，请重试']);
    }


    /**
     *小程序组件内容删除
     * @Author   jiating
     * @DateTime 2018-05-08
     * @param    int     $id  组件ID
     * @return   
     */
    public function componentDel() {
        $request = Request::instance();
        $id = $request->param('id');
        $del = Wxcomponentconf::where('id',$id)->delete();
        return json(['code'=>'1','message'=>'删除成功']);
    }

    /**
     * 新增模块数据提交
     * @Author   jiating
     * @DateTime 2018-05-07
     * @param    string     $name 板块名称
     * @param    string     $type 板块类型，如商品板块、轮播图等
     * @param    string     $displayType 板块显示类型，如2列还是1列，要和小程序端具体协商
     * @return   json
     */
    public function wxFrameConf() {
        $request = Request::instance();
        $param = $request->param();
        // return $param;

        if(isset($param['id']) && $param['id']) {  //模块设置-编辑
            $param['updateDate'] = date('Y-m-d H:i:s',time());
            $param['updateOper'] = session('member')['id'];
            $upd = Wxframeconf::where('id',$param['id'])->update($param);
            if($upd)
                return json(['code'=>'1','message'=>'保存成功']);
            return json(['code'=>'2','message'=>'出错，请重试']);
        }

        $id = BaseHelper::getUUID();
        $auto = [
            'id'=> $id,
            'page' => 'home',
            'createDate' => date('Y-m-d H:i:s',time()),
            'updateDate' => date('Y-m-d H:i:s',time()),
            'createOper' => session('member')['id'],
            'updateOper' => session('member')['id'],
            'tenantId' => session('TENANT_ID')
        ];
        $data = array_merge($auto,$param);
        $add = Wxframeconf::insert($data);
        if($add) {
            return json(['code'=>'1','message'=>'添加成功','id'=>$id]);
        } else {
            return json(['code'=>'2','message'=>'添加失败']);
        }
    }

    /**
     * 视频模块添加/编辑
     * @Author   jiating
     * @DateTime 2018-05-11
     */
    public function FrameReqVideo() {
        $request = Request::instance();
        $param = $request->param();

        $frame = $param['frame'];
        $upd_frame = Wxframeconf::where('id',$frame['id'])->update(['name'=>$frame['name']]);
        $WxComponentConf = $param['WxComponentConf'];
        if(Wxcomponentconf::where('frameId',$WxComponentConf['frameId'])->find()) {
            $WxComponentConf['updateDate'] = date('Y-m-d H:i:s',time());
            $WxComponentConf['updateOper'] = session('member')['id'];
            $save_component = Wxcomponentconf::where('frameId',$WxComponentConf['frameId'])->update($WxComponentConf);
        } else {
            $auto = [
                'id' => BaseHelper::getUUID(),
                'page' => 'home',
                'createDate' => date('Y-m-d H:i:s',time()),
                'updateDate' => date('Y-m-d H:i:s',time()),
                'createOper' => session('member')['id'],
                'updateOper' => session('member')['id'],
                'tenantId' => session('TENANT_ID')
            ];
            $data = array_merge($auto,$WxComponentConf);
            $save_component = Wxcomponentconf::insert($data);
        }

        if($save_component || $upd_frame) {
            return json(['code'=>'1','message'=>'保存成功']);
        } else{
            return json(['code'=>'2','message'=>'保存失败','test'=>$param]);
        }
    }

    /**
     * 模块删除
     * @Author   jiating
     * @DateTime 2018-05-08
     * @param    string     $frameId 模块ID
     * @return   json
     */
    public function wxFrameConfDel() {
        $request = Request::instance();
        $frameId = $request->param('frameId');
        $del1 = Wxframeconf::where('id',$frameId)->delete();
        $del2 = Wxcomponentconf::where('frameId',$frameId)->delete();
        if($del1)
            return json(['code'=>'1','message'=>'删除成功']);
        else 
            return json(['code'=>'2','message'=>'删除失败']);
    }

    /**
     * 拖动排序
     * @Author   jiating
     * @DateTime 2018-05-11
     */
    public function move() {
        $request = Request::instance();
        $param = $request->param();
        foreach ($param as $v) {
            Wxframeconf::where('id',$v['id'])->update(['orderNo'=>$v['orderNo']]);
        }
        return json(['code'=>'1','message'=>'排序成功']);
        return $param;
    }


    protected function defaultModel($tenantId) {
        $tenant = Tenant::field('category')->where('id',session('TENANT_ID'))->find();
        $default = Wxframeconftmp::where('category',$tenant['category'])->order('orderNo')->select();
        foreach ($default as $k => $v) {
            $component = Wxcomponentconftmp::where('frameId',$v['id'])->order('orderNo')->select();
            $default[$k]['sub'] = $component;
        }
        $this->assign('list',$default);        
    }

    /**
     * 检测所选类型是否已经设置了首页推荐
     * @param    int     $type 推荐显示内容类型，1-商品；2-文章；3-拼团；4-积分兑换
     */
    public function checkRecommendation() {
        $request = Request::instance();
        $param = $request->param();
        // return $param;
        $type = $param['type'];
        $storeId = $param['storeId'];

        switch ($type) {
            case '1':
                $count = \app\admin\model\Storeproduct::where(['store_id'=>$storeId,'recommendation'=>1])->count();
                $message = '商品尚未设置首页推荐，请到门店货架处设置';
                break;
            case '2':
                $count = \app\admin\model\Article::where(['tenantId'=>session('TENANT_ID'),'recommendation'=>1])->count();
                $message = '文章尚未设置首页推荐，请到文章管理处设置';
                break;
            case '3':
                $count = \app\admin\model\Groupproduct::where(['storeId'=>$storeId,'recommendation'=>1])->where('status','neq',2)->count();
                $message = '拼团尚未设置首页推荐，请到营销-拼团处设置';
                break;
            case '4':
                $count = \app\admin\model\Integralproducts::where(['storeId'=>$storeId,'recommendation'=>1])->where('status','neq',2)->count();
                $message = '积分商品尚未设置首页推荐，请到积分-积分兑换处设置';
                break;
        }
        if($count == 0) {
            return json(['code'=>'2','message'=>$message]);
        }
        return json(['code'=>'1','message'=>'']);
    }



}